#include "../library/socket.hh"
#include "../library/protocol.hh"
#include <iostream>
#include <string>

using namespace NM;
using namespace std;
using namespace DLIB_PROTO;

int main()
{
    Socket dispatcher = Socket(Socket::TCP4, "127.0.0.1", 2424);
    Protocol dispatcherNetwork;
    int serverPort;
    string serverAddress;
    Socket server;
    Protocol serverNetwork;

    // Connection with dispatcher
    dispatcher.connect();
    dispatcherNetwork.InitClient(&dispatcher);
    if (dispatcherNetwork.RecvConnectionConfirmation())
        cout << "Connection established successfully with Dispatcher!" << endl;
    else
    {
        cout << "Error while connecting to the Dispatcher!" << endl;
        return (1);
    }
    if (dispatcherNetwork.RecvServerInfo(&serverAddress, &serverPort))
        cout << "Server informations received from Dispatcher!" << endl;
    else
    {
        cout << "Error while receiving Server informations from Dispatcher!" << endl;
        return (1);
    }
    dispatcherNetwork.sendCode(CLOSE);

    // Connection with server
    server = Socket(Socket::TCP4, serverAddress, serverPort);
    server.connect();
    serverNetwork.InitClient(&server);
    if (serverNetwork.RecvConnectionConfirmation())
        cout << "Connection established successfully with Server!" << endl;
    else
    {
        cout << "Error while connecting to the Server!" << endl;
        return (1);
    }

    string name = "module_test.txt";
    char code[10000];
    int codeSize;

    FILE *module = fopen(name.c_str(), "r");
    codeSize = fread(code, 1, 10000, module);
    fclose(module);

    serverNetwork.SetModuleName(name);
    serverNetwork.SetModuleCode(code, codeSize);
    serverNetwork.SetModuleData(code, codeSize);
    cout << "Sending module..." << endl;
    sleep(3);
    serverNetwork.SendData();
    cout << "Module sent!" << endl;
    sleep(5);
    if (serverNetwork.RecvData())
        cout << "execution result received!" << endl;
    serverNetwork.sendCode(CLOSE);

    return (0);
}
